import sys
import os
import wx

#import model
from model import ImageModel
from wxfactory import WxFactory
from filelistctrl import FileListCtrl
from optionsdialog import OptionsDialog
import image
class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Gimg2py - pyEmbeddedImage Builder",
                         size=(500, 500))
        self.iModel=ImageModel()
        self.wxf = WxFactory(self)
        self.SetIcon(image.Icon("Camera_32"))
        self.SetMenuBar(self.CreateMenu())
        self.createToolBar().Realize()
        
        self.split = wx.SplitterWindow(self)
        self.split.SetMinimumPaneSize(20)
        p1 = wx.Panel(self.split)
        p2 = wx.Panel(self.split)
        self.split.SplitHorizontally(p1,p2,-100)
        
      # List control in p1 to display data
        self.list=FileListCtrl(p1,-1,model=self.iModel)
        
        s1=wx.BoxSizer(wx.HORIZONTAL)
        s1.AddF(self.list,wx.SizerFlags(1).Expand())
        self.list.Bind(wx.EVT_LIST_ITEM_SELECTED,self.OnListSel)
      # Some buttons in p1
        s1a=wx.GridSizer(rows=0,cols=1)
        buttonAdd=self.wxf.Button(p1,wx.ID_ADD,"add",tip="Add new images",
                  bind=self.OnAdd,sizer=s1a)
        buttonDel=self.wxf.Button(p1,wx.ID_DELETE,"delete",tip="Delete image",
                  bind=self.OnDelete,sizer=s1a)
        buttonUp=self.wxf.Button(p1,wx.ID_UP,"up",tip="Move up",
                  bind=self.OnMoveUp,sizer=s1a)
        buttonDown=self.wxf.Button(p1,wx.ID_DOWN,"down",tip="Move down",
                  bind=self.OnMoveDown,sizer=s1a)
        s1.Add(s1a,0)
        p1.SetSizer(s1)
        self.p1 = p1
      # Create a TextCtrl in p2 for capturing stdout
        self.capt = wx.TextCtrl(p2,
                    style=wx.TE_RICH|wx.TE_MULTILINE|wx.TE_READONLY)
        s2=wx.BoxSizer(wx.VERTICAL)
        s2.Add(self.capt,1,wx.EXPAND)
        p2.SetSizer(s2)
        self.CreateStatusBar()
        self.Layout()
        sys.stdout=RedirectText(self.capt)
      # Enable/disable menus
        self.SetEnable()  
        self.Bind(wx.EVT_CLOSE,self.OnClose)
        return
        
        
        
    def CreateMenu(self):
        wxf = self.wxf
        menubar=wx.MenuBar()
        # File menu
        menubar.Append(wxf.Menu(
            wxf.MenuItem(id=wx.ID_NEW,bind=self.OnNew),
            wxf.MenuItem(id=wx.ID_OPEN,bind=self.OnOpen),
            wxf.MenuSeparator(),
            wxf.MenuItem(id=wxf.ID_BUILD,text="Build",
                catalog="menu.build",bind=self.OnBuild),
            wxf.MenuSeparator(),
            wxf.MenuItem(id=wx.ID_SAVE,
                catalog="menu.save",bind=self.OnSave),
            wxf.MenuItem(id=wx.ID_SAVEAS,
                catalog="menu.saveas",bind=self.OnSaveAs),
            wxf.MenuSeparator(),
            wxf.MenuItem(id=wx.ID_EXIT,text="Exit",bind=self.OnExit)
                 ),
            "&File")
        
        # Edit menu
        menubar.Append(wxf.Menu(
          wxf.MenuItem(id=wx.ID_ADD,catalog="menu.add",bind=self.OnAdd),
          wxf.MenuItem(id=wx.ID_DELETE,catalog="menu.delete",bind=self.OnDelete),
          wxf.MenuSeparator(),
          wxf.MenuItem(id=wx.ID_UP,text="Move Up",
               catalog="menu.up",bind=self.OnMoveUp),
          wxf.MenuItem(id=wx.ID_DOWN,text="Move Down",
               catalog="menu.down",bind=self.OnMoveDown),
          wxf.MenuSeparator(),
          wxf.MenuItem(id=wx.ID_ANY,text="Options",
               catalog="menu.opt",bind=self.OnOptions)),
           "&Edit")
        # Help menu
        menubar.Append(wxf.Menu(
            wxf.MenuItem(id=wx.ID_ABOUT,catalog="Menu.About",
                bind=self.OnAbout)),
          "&Help")
        return menubar
    def createToolBar(self):
        toolbar = self.CreateToolBar()
        toolbar.AddSimpleTool(wx.ID_NEW,
                image.Bitmap("new_page"),"Create new file")
        toolbar.AddSimpleTool(wx.ID_OPEN,
                image.Bitmap("open_doc"),"Open existing file")
        toolbar.AddSimpleTool(self.wxf.ID_BUILD,
                image.Bitmap("process"),"Build embedded image file")
        toolbar.AddSimpleTool(wx.ID_SAVE,
                image.Bitmap("save"),"Save embedded image file")
        return toolbar
        
    def OnMenu(self,e):
        item=self.GetMenuBar().FindItemById(e.GetId())
        print("%s clicked" % item.GetLabel())
        
    def OnNew(self,e):
        if not self.CanDestroy(): return
        self.iModel = ImageModel() # have a new model
        self.list.Clear(self.iModel)
        self.SetEnable()  
        
    def OnOpen(self,e):
        if not self.CanDestroy(): return
        filter = "Python files (*.py)|*.py"
        file = self.iModel.getOption("pyfile")
        if file == None: file = (os.getcwd(),"")
        else: file = os.path.split(file)
        dialog=wx.FileDialog(None,"Open",file[0],file[1],
            wildcard=filter,
            style=wx.FD_OPEN|wx.FD_FILE_MUST_EXIST)    
        if dialog.ShowModal() == wx.ID_OK :
            self.OnNew(e)
            if not self.iModel.doLoadFile(dialog.GetPath(),self.list):
                self.OnNew(e)
        self.SetEnable()  
        
    def OnBuild(self,e):
        self.capt.Clear()
        self.iModel.doBuild(self.list.GetFileList())
        self.SetEnable()  
            
    def OnSave(self,e):
        if self.iModel.getOption("pyfile") == None:
            self.OnSaveAs(e)
            return
        self.iModel.doSave()
        self.SetEnable()  
        
    def OnSaveAs(self,e):
        filter = "Python files (*.py)|*.py"
        file = self.iModel.getOption("pyfile")
        if file == None: file = (os.getcwd(),"")
        else: file = os.path.split(file)
        dialog=wx.FileDialog(None,"Save as...",file[0],file[1],
            wildcard=filter,
            style=wx.SAVE|wx.CHANGE_DIR|wx.OVERWRITE_PROMPT)
        if dialog.ShowModal() == wx.ID_OK:
            self.iModel.setOption("pyfile",dialog.GetPath())    
            self.iModel.doSave()
        self.SetEnable()      
    
    def OnExit(self,e):
        self.Close()
            
    def OnAdd(self,e): 
        # Show File open Dialog
        filter="Image files (*.png;*.jpg;*.ico;*.bmp)|*.png;*.jpg;*.ico;*.bmp|"\
               "All files (*.*)|*.*"
        dialog=wx.FileDialog(None,"Choose files to add",
               self.iModel.getOption("cdir"),wildcard=filter,
               style=wx.FD_OPEN|wx.FD_MULTIPLE|wx.FD_FILE_MUST_EXIST  )
        if dialog.ShowModal() == wx.ID_OK :
           for file in dialog.GetPaths():
               self.list.Add(file)
           
           
        dialog.Destroy()
        self.SetEnable()  
        
    def OnDelete(self,e):
        self.list.Delete()
        self.iModel.doChange()
        self.SetEnable()  
        
    def OnMoveUp(self,e):
        self.list.MoveUp()
        self.iModel.doChange()
        self.SetEnable()  
        
    def OnMoveDown(self,e):
        self.list.MoveDown()
        self.iModel.doChange()
        self.SetEnable()  
        
    def OnOptions(self,e):
        flags = dict((key,self.iModel.getOption(key,default=False)) 
             for key in ("name","inclext","catalog","compat","icon"))
        optdialog = OptionsDialog(flags)
        
        if optdialog.ShowModal() == wx.ID_OK:
           for key,flag in optdialog.GetOptions().items():
               self.iModel.setOption(key,flag)
        optdialog.Destroy()
        self.SetEnable()  
    
    def OnAbout(self,e):
        about = wx.AboutDialogInfo()
        about.SetName("Gimg2py")
        about.SetVersion("0.1.0")
        about.SetCopyright("(C) 2010 Ray Folwell <ray@folwell.org.uk>")
        about.SetDescription(
        "Some images by DryIcons\n http://dryicons.com"
        )
        
        wx.AboutBox(about)
    
    def OnListSel(self,e):
        self.SetEnable()

    # Enable/Disable menus and buttons
    def SetEnable(self):
        self.EnableItem(wx.ID_DELETE,self.list.CanDelete())
        self.EnableItem(wx.ID_UP,self.list.CanMoveUp())
        self.EnableItem(wx.ID_DOWN,self.list.CanMoveDown())
        self.EnableItem(self.wxf.ID_BUILD,self.iModel.CanBuild())
        self.EnableItem(wx.ID_SAVE,self.iModel.CanSave())
        self.EnableItem(wx.ID_SAVEAS,self.iModel.CanSaveAs())
     
    def EnableItem(self,id,enable):
        for item in (self.GetMenuBar().FindItemById(id),
                     self.p1.FindWindowById(id)):
            if item != None: item.Enable(enable)
        self.GetToolBar().EnableTool(id,enable)
        
    def CanDestroy(self):
        if self.iModel.CanDestroy(): return True
        dlgtext = "%s changes made to file ?\n%s" % (
            "Save" if self.iModel.CanSave() else "Build and save",
            self.iModel.getOption("pyfile","New file"))
        result = wx.MessageDialog(None,dlgtext,"Confirm",
            wx.YES|wx.NO|wx.CANCEL|wx.ICON_QUESTION).ShowModal()   
        if result == wx.ID_CANCEL: return False
        if result == wx.ID_NO: return True
        if not self.iModel.CanSave(): self.OnBuild(None)
        self.OnSave(None)
        return self.iModel.CanDestroy()
                
    def OnClose(self,e):
        if not e.CanVeto(): self.Destroy()
        if self.CanDestroy(): 
            self.Destroy()
        else:
            e.Veto()
           
class RedirectText(object):
    def __init__(self,aWxTextCtrl):
        self.out=aWxTextCtrl
    def write(self, string):
        wx.CallAfter(self.out.WriteText, string)
        
        
class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame()
        self.SetTopWindow(frame)
        frame.Show(True)
        return True
        
def main():
    app = MyApp(redirect=True)
    app.MainLoop()

if __name__ == '__main__':
    main()
    